<template>
  <div class="container">
    <VerticalLayout>
      <!-- 插入搜索组件 -->
      <template #search>
        <el-space alignment="center">
          <DynamicQueryForm
            :show-match-range="false"
            :extra-fields="extraField(users, customerTypes)"
            :columns-values="columnsValues"
            @submit="onSubmit"
          />
        </el-space>
      </template>
      <!-- 插入表格组件 -->
      <template #table>
        <CustomTable
          v-if="userApp?.roles"
          ref="customTableRef"
          :actions="listCustomer"
          :defaultParams="rolesDefaultParams"
          :columns="columns"
          show-selection
          show-pagination
          @selection-change="onSelectionChange"
        >
          <!-- 左边功能 -->
          <template #action-left>
            <el-button type="primary" :icon="Plus" @click="onAdd">添加客户</el-button>
          </template>

          <!-- 右边功能 -->
          <template #action-right>
            <!-- <el-button :icon="Refresh" circle /> -->
          </template>

          <template #table-top v-if="selections.length > 0">
            <el-alert :closable="false">
              <template #title>
                {{ `您已选择${selections.length}条数据` }}
              </template>
            </el-alert>
          </template>
          <!-- 客户档案 -->
          <template #customerSlot="{ row }">
            <RowSlots slotName="customerSlot" :row="row" @payHistory="payHistory" />
          </template>

          <!-- 客户类别 -->
          <template #categorySlot="{ row }">
            <RowSlots slotName="categorySlot" :row="row" />
          </template>

          <!-- 客户分组 -->
          <template #groupSlot="{ row }">
            {{ getGroup(row.group) }}
          </template>

          <!-- 业务员 -->
          <template #salesmanSlot="{ row }">
            <RowSlots slotName="salesmanSlot" :row="changeRowToSalesman(row)" />
          </template>

          <!-- 备注 -->
          <template #remarkSlot="{ row }">
            <RowSlots
              slotName="remarkSlot"
              :row="row"
              @showCustomerFollowUp="showCustomerFollowUp"
            />
          </template>

          <template #operationSlot="{ row }">
            <el-space size="small" direction="vertical">
              <el-dropdown
                trigger="click"
                placement="bottom-end"
                @command="(cmd: any) => handleCommand(cmd, row)"
              >
                <el-button type="primary" text size="small">
                  <el-icon><Setting /></el-icon>
                  设置
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item type="primary" :icon="Edit" command="manageArchive"
                      >管理档案</el-dropdown-item
                    >
                    <!-- 非销售角色展示 -->
                    <el-dropdown-item
                      v-if="!loginUserRoles.includes('saleUser')"
                      type="primary"
                      :icon="Edit"
                      command="changeSalesman"
                      >分配业务</el-dropdown-item
                    >
                    <el-dropdown-item v-if="isDev" type="danger" :icon="DeleteFilled" command="del"
                      >删除</el-dropdown-item
                    >

                    <template v-if="isSaleUser">
                      <el-dropdown-item
                        v-if="+row.topStatus === 1"
                        :icon="SemiSelect"
                        command="cancelTop"
                        :danger="true"
                      >
                        取消置顶
                      </el-dropdown-item>
                      <el-dropdown-item v-else :icon="Top" command="top"> 置顶 </el-dropdown-item>
                    </template>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </el-space>
          </template>
        </CustomTable>
      </template>
    </VerticalLayout>

    <!-- 筛选弹窗 -->
    <FilterTable ref="filterTableRef" />
    <!-- 查看客户档案 -->
    <CustomerDialog @ok="customTableRef?.refresh" ref="customerDialogRef" />
    <!-- 添加客户 -->
    <CustomerRecord ref="customerRecordRef" @ok="customTableRef?.refresh" />
    <!-- 用户下单记录 -->
    <CustomerOrderHistory ref="customerOrderHistoryRef" />
    <!-- 跟进详情 -->
    <CustomerFollowUp ref="customerFollowUpRef" @ok="customTableRef?.refresh" />
    <!-- 更换业务员弹窗 -->
    <ChangeSalesmanDialog
      :salesmanList="users"
      ref="changeSalesmanDialogRef"
      @ok="customTableRef?.refresh"
    />
    <!-- 置顶弹窗 -->
    <TopCustomDialog ref="topCustomDialogRef" @ok="customTableRef?.refresh" />
  </div>
</template>

<script setup lang="ts">
import { Plus, Edit, DeleteFilled, Top, SemiSelect } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { columns } from './columns';
import { cloneDeep } from 'lodash';
import { delCustomer, listCustomer } from '../../../api/customers';
import CustomerDialog from '../../../components/Alert/customerDialog.vue';
import { computed, onMounted, ref } from 'vue';
import { columnsValues, extraField } from './searchOptions';
import { useCustomStore } from '../../../store/modules/custom';
import { useYw } from '../../../hooks/useYw';
import useUserStore from '../../../store/modules/user';
const { ywList: users } = useYw();

const customStore = useCustomStore();
const customerTypes = computed(() => customStore.customerTypesOptions);

const userApp = useUserStore();
const isSaleUser = computed(() => userApp.roles.includes('saleUser'));
// 获取当前环境
// @ts-ignore
const env = import.meta.env;
// 开发环境下提供删除
const isDev = env.VITE_ENV === 'development';

const changeSalesmanDialogRef = ref();
// table
const customTableRef = ref();
// 筛选
const filterTableRef = ref();
// 添加客户
const customerDialogRef = ref();
// 客户档案
const customerRecordRef = ref();
// 用户下单记录
const customerOrderHistoryRef = ref();
// 跟进详情
const customerFollowUpRef = ref();
// 置顶弹窗
const topCustomDialogRef = ref();

const changeRowToSalesman = (row: any) => {
  if (row.salesman) {
    row.salesmanName = row.salesman.salesmanName;
    row.salesmanDept = row.salesman.dept.deptName;
    row.salesmanId = row.salesman.salesmanId;
  }
  return row;
};

// 当前登录的是什么角色
const loginUserRoles = computed(() => {
  return userApp?.roles;
});

// 如果是销售登陆，只能查看销售自己的客户
const rolesDefaultParams = computed(() => {
  if (loginUserRoles.value.includes('saleUser')) {
    return {
      salesmanId: userApp.id
    };
  }
  return {};
});

// 根据 row.group 查询出客户的分组
const getGroup = (group: string) => {
  if (group) {
    return customerTypes.value?.find((item: any) => item.value === group)?.label || '无分组';
  }
  return '无分组';
};

// 选中项
const selections = ref<any>([]);
const onSelectionChange = (selection: any[]) => {
  selections.value = selection;
};

// 添加客户
const onAdd = () => {
  customerDialogRef.value?.show(cloneDeep(selections.value));
};

// 查看订单记录
const payHistory = (row: any) => {
  customerOrderHistoryRef.value?.show(row);
};
// 显示跟踪备注
const showCustomerFollowUp = (row: any, typeCode: number) => {
  customerFollowUpRef.value?.show(row, typeCode);
};
// 更换业务员
const changeSalesman = (row: any) => {
  changeSalesmanDialogRef.value?.show(row);
};

const onEdit = (row: any) => {
  customerDialogRef.value?.show(cloneDeep(row));
};

const onDel = (row: any) => {
  ElMessageBox.confirm('确定删除选中客户吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    delCustomer(row.customerId).then((res: any) => {
      if (res.code === 200) {
        ElMessage.success('删除成功');
        customTableRef.value?.search();
      }
    });
  });
};

const onSubmit = (form: any) => {
  customTableRef.value?.search(form);
};

// 处理设置操作
const handleCommand = (cmd: any, row: any) => {
  switch (cmd) {
    case 'top':
      // 置顶操作
      topCustomDialogRef.value?.show(row);
      break;
    case 'cancelTop':
      // 取消置顶操作
      topCustomDialogRef.value?.cancelTop(row);
      break;
    case 'changeSalesman':
      changeSalesman(row);
      break;
    case 'del':
      onDel(row);
      break;
    case 'manageArchive':
      onEdit(row);
      break;
    default:
      break;
  }
};

onMounted(() => {
  // 初始化类别数据
  customStore.initCustom();
});
</script>

<style scoped lang="scss">
.container {
  padding: 16px;

  .productName {
    font-weight: bold;
  }

  .alertFpBtn {
    padding-left: 0;
    padding-right: 0;
  }

  .payCount {
    cursor: pointer;
  }

  .remarkBox {
    .newReamark {
      display: block;
      text-wrap: wrap;
      text-align: left;
      line-height: 18px;
      font-size: 13px;
      margin-bottom: 5px;
    }
  }
}
</style>
